package com.openbravo.pos.reports;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.data.loader.BaseSentence;
import com.openbravo.pos.base.AppLocal;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

public class Report {
     private String name;
     private String resourceBundle;
     private ReportFields fields;
	
     private JasperReport jr = null;
     private Map reportparams = new HashMap();
     
     public Report(String name) {
		super();
		this.name = name;
	}
     
     public Report resourceBundle(String b){
    	 this.resourceBundle=b;
    	 return this;
     }

    
    public Report fields(ReportFields f){
    	this.fields=f;
    	return this;
    }
    
    public Report reportParam(String name,Object v){
    	reportparams.put(name, v);
    	return this;
    }
    
     
    public Report compileReport()throws Exception{
    	 try {     
             
             InputStream in = getClass().getResourceAsStream(name + ".ser");
             if (in == null) {      
                 // read and compile the report
                 JasperDesign jd = JRXmlLoader.load(getClass().getResourceAsStream(name + ".jrxml"));            
                 jr = JasperCompileManager.compileReport(jd);    
             } else {
                 // read the compiled report
                 ObjectInputStream oin = new ObjectInputStream(in);
                 jr = (JasperReport) oin.readObject();
                 oin.close();
             }
         } catch (Exception e) {
             jr = null;
             throw e;
             
         }  
    	 return this;
    }
    
    public JasperPrint fillReport(JRDataSource data) throws BasicException, JRException{       

        if (resourceBundle != null) {
              reportparams.put("REPORT_RESOURCE_BUNDLE", ResourceBundle.getBundle(resourceBundle));
        } 
       return JasperFillManager.fillReport(jr, reportparams, data);    
    }
    
    public  byte[]  PDF(JRDataSource data) throws JRException, BasicException{
    	return JasperExportManager.exportReportToPdf(fillReport(data));
    }
 
}
